<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class Device extends CI_Controller {

             public function __construct() {
	        parent::__construct();
	        $this->load->model('M_device_type');
	        $this->load->model('M_device');
	        $this->load->model('M_device_task');
             }
             //添加设备类型
	public function add_device_type()
	{
	            $typeid = (int) $this->input->get_post('typeid'); //设备id
                         $typename = $this->input->get_post("typename", true);//类型名称
                         $depid = $this->input->get_post("depid", true);//部门名称
                         $isshow = $this->input->get_post("isshow", true);//是否显示 0不显示1显示
		if(empty($typename)){
		       exit(json_encode(array('code'=>1,'info'=>'类型名称不能为空')));
		}
		if(empty($depid)){
		       exit(json_encode(array('code'=>1,'info'=>'部门id不能为空')));
		}
		$data = array(
			'device_type_name'=>$typename,
			'department_id'=>$depid,
			'is_show'=>$isshow,
			);
		if($typeid){
		    $sql = "SELECT count(*) as count from t_device_type WHERE device_type_name = '{$typename}'" . ($typeid ? " AND device_type_id != {$typeid}" : '');
		    $res = $this->db->query($sql)->row_array();
			if($res['count']<>"0"){
				exit(json_encode(array('code'=>1,'info'=>'类型已存在')));
			}
			$result = $this->M_device_type->update('t_device_type', $data, array('device_type_id'=>$typeid));
			if($result !== false){
				exit(json_encode(array('code'=>0,'info'=>'修改成功')));
			}
			exit(json_encode(array('code'=>1,'info'=>'修改失败')));
		}else{
			$sql = "SELECT count(*) as count from t_device_type WHERE device_type_name = '{$typename}'";
		    	$res = $this->db->query($sql)->row_array();
			if($res['count']<>0){
				exit(json_encode(array('code'=>1,'info'=>'类型已存在')));
			}
			$id = $this->M_device_type->saveData($data);
			if($id){
				exit(json_encode(array('code'=>0,'info'=>'添加成功')));
			}
			exit(json_encode(array('code'=>1,'info'=>'添加失败')));
		}
             }
              //类型列表
             public function type_list(){
             	//   设备类型  设备车间
             	$page       = getParam($this->input->get_post("page"),'int',1);
		$typename = $this->input->get_post("typename");//设备类型
		$deptid = $this->input->get_post("deptid");//车间
		$sel = $this->input->get_post("sel");//
		// echo $sel;exit();
		$per_page   = 2;//每一页显示的数量
		$this->load->library("common_page");
		$where = " where 1=1";
		if(!empty($typename)){
			$where.=" AND t.device_type_name like '%".$typename."%'";
		}
		if(!empty($deptid)){
			$where.=" AND t.department_id = {$deptid}";
		}
		$total = $this->M_device->getTypeCount($where);
		$page_string = $this->common_page->page_string($total, $per_page, $page);
		$limit   = ($page-1)*$per_page;
		$limit  .=",{$per_page}";
		if($sel==1){
		$sql = "SELECT device_type_id as id,device_type_name as text FROM t_device_type";
		$list = $this->M_device->querylist($sql);
	}else{
		$list   = $this->M_device->getTypeList($where,$limit);
		// $list = array();
		// foreach ($arr as $key => $value) {
		// 	$list[$value['device_type_id']] = $value['device_type_name'];
		// }
	}
	// var_dump($page_string);exit();
            		exit(json_encode(array('code'=>0,'data'=>$list,'result_page'=>$page_string,'info'=>'成功')));
		
		// var_dump($list);exit();
        		// exit(result_to_towf_new($list, 1, '成功', $page_string));
             }
             /**
	 * 删除设备类型
	*/
	public function del_devicetype(){
		// $id = (int) $this->input->get_post('typeid');//设备类型id
		$id = $_POST['typeid'];
		$id = implode(',',$id);
                          $sql = "SELECT device_id FROM t_device WHERE device_type_id in ".'('."$id".')'."";
                          $result1 = $this->M_device->querylist($sql);
                          if(empty($result1)){
			$sql = "DELETE FROM t_device_type WHERE device_type_id in ".'('."$id".')'." LIMIT 1";
                                       $result = $this->db->query($sql);
			if($result !== false){
				exit(json_encode(array('code'=>0,'info'=>'删除成功')));
			}
			exit(json_encode(array('code'=>1,'info'=>'删除失败')));
                          }else{
			exit(json_encode(array('code'=>1,'info'=>'此类型下有设备不能删除')));

                          }
	}
             //添加新设备
             public function add_device(){
             	$id = (int) $this->input->get_post('deviceid'); //设备id
		$devicename = $this->input->get_post('devicename');//设备类型id
		$typeid = $this->input->get_post('typeid');//设备类型id
		$grid = $this->input->get_post('grid');//设备所属网格id
		$x = $this->input->get_post('device_x');//x
		$y = $this->input->get_post('device_y');//y
		$smilegrid = $this->input->get_post('smilegrid');//y
		$workid = $this->input->get_post('workid');//巡检岗位id
		$workname = $this->input->get_post('workname');//巡检岗位名称
		$wxworkid = $this->input->get_post('wxworkid');//维修岗位id
		$wxworkname = $this->input->get_post('wxworkname');//维修岗位名称
		$isopen = $this->input->get_post('isopen');//是否启用巡检0否1是
	             $cycle = $this->input->get_post('xjcycle');//巡检周期
	             $execute = $this->input->get_post('execute');//执行周期
		$deptinfo = $this->M_device->getDeptName($typeid);
        		$sqlid = "select max(device_id) as max_id from t_device";
        		$deviceID = $this->db->query($sqlid)->row_array();
		if(empty($devicename)){
			exit(json_encode(array('code'=>1,'info'=>'设备名不能为空')));
		}
		if(empty($workid)){
			exit(json_encode(array('code'=>1,'info'=>'请选择岗位')));
		}
		if(empty($typeid)){
			exit(json_encode(array('code'=>1,'info'=>'请选择设备类型')));
		}
		$data = array(
				'device_name'=>$devicename,
				'xj_cycle'=>$cycle,//巡视周期
				'device_x'=>$x,
				'device_y'=>$y,
				'smile_grid'=>$smilegrid,
				'device_type_id'	=>$typeid,
				'grid_id'	=>$grid,
				'xj_post_id'=>$workid,
				'xj_post_name'=>$workname,
				'wx_post_id'=>$wxworkid,
				'wx_post_name'=>$wxworkname,
				'execute'=>$execute,
				'is_open'=>$isopen,
			);
		if($id){
		    $sql = "SELECT count(*) as count from t_device WHERE device_name = '{$devicename}'" . ($id ? " AND device_id != {$id}" : '');
		    $res = $this->db->query($sql)->row_array();
		    // var_dump($res);exit();
			if($res['count']<>"0"){
				exit(json_encode(array('code'=>1,'info'=>'设备名称已存在')));
			}
			$result = $this->M_device->update('t_device', $data, array('device_id'=>$id));
			if($result !== false){
				exit(json_encode(array('code'=>0,'info'=>'修改成功')));
			}
			exit(json_encode(array('code'=>1,'info'=>'修改失败')));
		}else{
			$code_arr = array(
			             'cz' => substr('131785',0,4),  
			             'ks' =>  $deptinfo['deptid'],
			             'qy' =>  $grid,  
			             'lx' =>  $typeid,  
			             'xx' =>  $wxworkid,  
			             'xh' =>  $deviceID['max_id']?$deviceID['max_id']+1:1
				);
	       		$number = $this->random_code($code_arr);//生成20位编码
			$data['device_number'] = $number;
			$data['user_id'] = 1;
			$data['addtime'] = time();
		    	$sql = "SELECT count(*) as count from t_device WHERE device_name = '{$devicename}'";
		    	$res = $this->db->query($sql)->row_array();
			if($res['count']<>0){
				exit(json_encode(array('code'=>1,'info'=>'设备名称已存在')));
			}
			$id = $this->M_device->saveData($data);
			if($id){
				exit(json_encode(array('code'=>0,'data'=>$id,'info'=>'添加成功')));
			}
			exit(json_encode(array('code'=>1,'info'=>'添加失败')));
		}

             }
             //设备列表
             public function device_list(){
             	$page       = getParam($this->input->get_post("page"),'int',1);
             	$per_page   = 2;//每一页显示的数量
		$devicename = $this->input->get_post("devicename");//设备名称
		$typeid = $this->input->get_post("typeid");//设备类型
		$grid = $this->input->get_post("grid");//所在网格
		$this->load->library("common_page");
		$where = " where 1=1";
		if(!empty($devicename)){
			$where.=" AND d.device_name like '%".$devicename."%'";
		}
		if(!empty($typeid)){
			$where.=" AND d.device_type_id = {$typeid}";
		}
		if(!empty($grid)){
			$where.=" AND d.grid_id = {$grid}";
		}
		$total = $this->M_device->getDeviceCount($where);
		$page_string = $this->common_page->page_string($total, $per_page, $page);
		$limit   = ($page-1)*$per_page;
		$limit  .=",{$per_page}";
		$list   = $this->M_device->getDeviceList($where,$limit);
            		exit(json_encode(array('code'=>0,'data'=>$list,'info'=>'成功')));
        		// exit(result_to_towf_new($list, 1, '成功', $page_string));
             }
             /**
	 * 删除设备
	*/
	public function del_device(){
		// $id = (int) $this->input->get_post('deviceid');
		$id = $_POST['deviceid'];
		$id = implode(',',$id);
                          $sql = "update t_device_report set device_id = null,device_status=0 where device_id in ".'('."$id".')'."";
                          $result1 = $this->db->query($sql);
                          if($result1){
			$sql = "DELETE FROM t_device WHERE device_id in ".'('."$id".')'." LIMIT 1";
                                       $result = $this->db->query($sql);
			if($result !== false){
				exit(json_encode(array('code'=>0,'info'=>'删除成功')));
			}
			exit(json_encode(array('code'=>1,'info'=>'删除失败')));
                          }else{
			exit(json_encode(array('code'=>1,'info'=>'解除关联失败')));

                          }
	}

             /**
	 * 生成18位编码
	*/
	public function random_code($code_arr){
		$cz = str_pad($code_arr['cz'],4,'0',STR_PAD_LEFT);   //车站编码
		$ks = str_pad($code_arr['ks'],2,'0',STR_PAD_LEFT);   //设备责任科室编码
		$qy = str_pad($code_arr['qy'],3,'0',STR_PAD_LEFT);   //设备区域编码
		$lx = str_pad($code_arr['lx'],3,'0',STR_PAD_LEFT);   //设备类型编码
		$xx = str_pad($code_arr['xx'],3,'0',STR_PAD_LEFT);   //设备维修编码
		$xh = str_pad($code_arr['xh'],6,'0',STR_PAD_LEFT);   //设备序号编码
		return $cz.$ks.$qy.$lx.$xx.$xh;
	}

	//设备报修记录
	public function report_list(){
	         $page       = getParam($this->input->get_post("page"),'int',1);
                      $per_page   = 2;//每一页显示的数量
                      $devicename = $this->input->get_post("devicename");//设备名称
                      $status = $this->input->get_post("status");//设备名称
                      $devicetype = $this->input->get_post("devicetype");//设备类型
                      $grid = $this->input->get_post("grid");//设备网格
                      $starttime = $this->input->get_post("starttime");//开始时间
                      $endtime = $this->input->get_post("endtime");//结束时间
                      $starttime = strtotime($starttime);
                      $endtime = strtotime($endtime);
                      $this->load->library("common_page");
                      $where = 'WHERE r.is_show=1';
                      if(!empty($devicename)){
                          $where.=" AND r.device_name="."'"."$devicename"."'";
                      }
                       if(!empty($devicetype)){
                          $where.=" AND r.device_type_id={$devicetype}";
                      }
                       if(!empty($grid)){
                          $where.=" AND d.grid_id={$grid}";
                      }
                       if(!empty($starttime) && !empty($endtime)){
                          $where.=" AND r.report_addtime >={$starttime} AND r.report_addtime<={$endtime}";
                      }
                      if(!empty($status)){
                      	$where.=" AND r.report_status={$status}";
                      }
                      $total = $this->M_device->getReportCount($where);
	         $page_string = $this->common_page->page_string($total, $per_page, $page);
	         $limit   = ($page-1)*$per_page;
	         $limit  .=",{$per_page}";
                      $sql="SELECT r.report_id,r.device_name,t.device_type_name,g.grid_name,p.post_name,u.user_name,m.department_name,r.report_addtime,r.report_status FROM t_device_report r LEFT JOIN t_device_type t ON t.device_type_id=r.device_type_id LEFT JOIN t_device d ON d.device_id=r.device_id LEFT JOIN t_grid g ON g.grid_id=d.grid_id LEFT JOIN t_user u ON u.user_id=r.report_user_id LEFT JOIN t_department m ON m.department_id=u.department_id LEFT JOIN t_post p ON p.post_id=d.wx_post_id {$where} limit {$limit}";
                      $data = $this->M_device->querylist($sql);
                      foreach ($data as &$value) {
                      	$value['report_addtime'] = date('Y-m-d H:i:s',$value['report_addtime']);
                      }
                      var_dump($page_string);exit();
                      exit(json_encode(array('code'=>0,'data'=>$data,'info'=>'成功','result_page'=>$page_string)));
	}
	/**设备故障上报详情
	 *@param $PID
	 *@param $mtid
	 */
	public function device_report_details(){
		$reportid = $this->input->get_post("reportid", true);//上报ID
		if(empty($reportid)){
		       exit(json_encode(array('code'=>1,'info'=>'设备维护reportid不能为空！')));
		}
		$sql = "SELECT status FROM t_device_repairtask WHERE report_id={$reportid}";
		$status = $this->db->query($sql)->row_array();
		$sql = "select d.device_name,r.report_remark,t.device_type_name,g.grid_name,r.report_file,r.report_voice,r.report_status,r.report_id from t_device_report r left join t_device d on d.device_id=r.device_id left join t_device_type t on t.device_type_id=r.device_type_id left join t_grid g on g.grid_id=d.grid_id where report_id={$reportid}";
		$list = $this->db->query($sql)->row_array(); //上报的信息  设备名称  留言  附件  语音 上报状态
		if($list['report_status']==1 || $list['report_status']==2 || $list['report_status']==3 || $list['report_status']==4){
			$sql = "SELECT report_user_name,report_addtime,report_remark FROM t_device_report WHERE report_id={$reportid}";
			$list1 = $this->db->query($sql)->row_array();
			$sql1 = "SELECT u.user_name as username,t.task_result as result,t.task_addtime as addtime,t.task_remark as remark,2 as status,t.task_time as tasktime,t.task_donetime as taskdonetime,t.task_status as taskstatus  FROM t_device_repairtask k LEFT JOIN t_device_report r ON r.report_id=k.report_id LEFT JOIN t_device_task t ON t.repairtask_id=k.repairtask_id LEFT JOIN t_user u ON u.user_id=t.user_id WHERE r.report_id={$reportid} AND the_task_type=2";
			$list2 = $this->M_device->querylist($sql1);
			$sql2 = "SELECT u.user_name as username,t.task_result as result,t.task_addtime as addtime,t.task_remark as remark,3 as status,t.task_time as tasktime,t.task_donetime as taskdonetime,t.task_status as taskstatus  FROM t_device_inspecttask i LEFT JOIN t_device_report r ON r.report_id=i.report_id LEFT JOIN t_device_task t ON t.inspecttask_id=i.inspecttask_id LEFT JOIN t_user u ON u.user_id=t.user_id WHERE r.report_id={$reportid} AND the_task_type=1";
			$list3 = $this->M_device->querylist($sql2);
		}
		$file = $list['report_file'];
	             $a = explode(',', $file);
	             $list['report_file'] = $a;
		if(!empty($list1)){
			$data = array(
					array(
	                                                    'username'=>$list1['report_user_name'],
	                                                    'result'=>"1",
	                                                    'addtime'=>date('Y-m-d H:i:s',$list1['report_addtime']),
	                                                    'remark'=>$list1['report_remark'],
					'status'=>"1",
	                                                    ),

				);
		}
		if(!empty($list2)){
			foreach ($list2 as $key => $value) {
				$value['addtime'] = date('Y-m-d H:i:s',$value['addtime']);
				$value['tasktime'] = empty($value['tasktime'])?"":date('Y-m-d H:i:s',$value['tasktime']);
				$value['taskdonetime'] = empty($value['taskdonetime'])?"":date('Y-m-d H:i:s',$value['taskdonetime']);
				array_push($data, $value);
			}
		}
		if(!empty($list3)){
			foreach ($list2 as $key => $value) {
				$value['addtime'] = date('Y-m-d H:i:s',$value['addtime']);
				$value['tasktime'] = empty($value['tasktime'])?"":date('Y-m-d H:i:s',$value['tasktime']);
				$value['taskdonetime'] = empty($value['taskdonetime'])?"":date('Y-m-d H:i:s',$value['taskdonetime']);
				array_push($data, $value);
			}
		}
		$sort_key='addtime';
			if(!empty($data)){
				foreach ($data as $row_array)
				{  
					$key =  $row_array[$sort_key];
					$key_array[] = $key;
				}  
				array_multisort($key_array,SORT_ASC,$data);
			}
		$res=array();
		$res['devinfo']=$list;
		$res['taskinfo']=$data;
		$res['status']=$status['status'];
                     	exit(json_encode(array('code'=>0,'data'=>$res,'info'=>'成功')));
		// $this->printJson_data($res);
	}
	//任务处理
	public function get_repairedevice_result(){
		$reoprtid = $this->input->get_post("reoprtid", true);//上报id
		$type = $this->input->get_post("type", true);//1转发2撤销
		$userid = $this->input->get_post("userid", true);//用户id
		$uid = $this->input->get_post("uid", true);//任务接收人
		$endtime = $this->input->get_post("endtime", true);//任务要求完成时间
		if(empty($type)){
			exit(json_encode(array('code'=>1,'info'=>'类型不能为空')));
		}
		if(empty($userid)){
			exit(json_encode(array('code'=>1,'info'=>'userid不能为空')));
		}
		if(empty($reoprtid)){
			exit(json_encode(array('code'=>1,'info'=>'上报id不能为空')));
		}
		
		$sql = "select * from t_device_report where report_id='{$reoprtid}'"; 
		$list = $this->db->query($sql)->row_array();
		$sql = "SELECT role_id FROM t_role WHERE role_name='指挥中心'";
		$id = $this->db->query($sql)->row_array();
		$id = implode(',', $id);
		$sql = "SELECT device_id FROM t_device_report WHERE report_id={$reoprtid}";
		$deviceid = $this->db->query($sql)->row_array();
		if($type==1){
			if(empty($uid)){
				exit(json_encode(array('code'=>1,'info'=>'任务接收人不能为空')));
			}
                                       //转发
                                       $sql = "select find_in_set({$id},has_role) as isexist from t_user WHERE user_id={$userid}";
			$role = $this->db->query($sql)->row_array();
			if($role['isexist']<>0){
				$sql = "SELECT * FROM t_device_task WHERE user_id={$uid}";
				$user = $this->db->query($sql)->row_array();
				if(!empty($user)){
					exit(json_encode(array('code'=>1,'info'=>'此人已有这条任务记录不能再下发')));
				}
                                                   if($list['report_flag']==0&&$list['report_status']=1){
					$sqltid = "select repairtask_id from t_device_repairtask where report_id='{$reoprtid}'";
					$tid = $this->db->query($sqltid)->row_array();
					$taskid=$tid['repairtask_id'];
					$sqlr = "select * from t_device_task where repairtask_id='{$taskid}' and the_task_type=2 order by task_addtime DESC";
					$r = $this->M_device->querylist($sqlr);
					$sqlrid = "select inspecttask_id from t_device_inspecttask where report_id='{$reoprtid}'";
					$rtid = $this->db->query($sqlrid)->row_array();
					if(!empty($rtid)){
						$sqlg = "select * from t_device_task where inspecttask_id='{$rtid['inspecttask_id']}' and the_task_type=1 order by task_addtime DESC";
						$g = $this->M_device->querylist($sqlg);
						if(!empty($g)){
							foreach ($g as $key => $value) {
								array_push($r, $value);
							}
						}
					}
					if(!empty($r)){
						$sort_key='task_addtime';
						foreach ($r as $row_array)
						{  
							$key =  $row_array[$sort_key];
							$key_array[] = $key;
						}  
						array_multisort($key_array,SORT_DESC,$r);
					}
					$sqlr = "select task_id,task_status,task_result,the_task_type from t_device_task where repairtask_id='{$taskid}' and the_task_type=2 and task_status=1 and task_result=0";
					$r = $this->M_device->querylist($sqlr);
					if(count($r)){
		       				exit(json_encode(array('code'=>1,'info'=>'此维修任务已经有人在做,无法下发!')));
					}
						$sqldet="select a.user_name,a.user_account,a.department_id,b.department_name from t_user a left join t_department b on b.department_id=a.department_id where a.user_id='{$uid}'";
						$det = $this->db->query($sqldet)->row_array();
						$data2=array(
						'repairtask_id'=>$taskid,
						'the_task_type'=>2,
						'user_id'=>$uid,
						'task_status'=>0,
						'task_time'=>0,
						'task_addtime'=>time(),
						'task_endtime'=>$endtime,
						);
					$insert_id2 = $this->M_device_task->saveData($data2);
					// $url ="#";//维修任务列表
					// $type ="devicemaintainnotice";
					// $content = $Info['remark'];
					// $title = $list['name'].'设备维修任务';//设备名称
					// $send = self::sendmess($p['LoginName'],$content,$det['LoginName'],$title,$url,$type);
					$nowtime=time();
					//修改任务状态
					$updsql = "UPDATE t_device_repairtask SET status=1,repairtask_is_open=1,repairtask_result=0,repairtask_user_id='{$userid}',repairtask_time='{$nowtime}' WHERE repairtask_id='{$taskid}'";
					$this->db->query($updsql);
					$updsql1 = "UPDATE t_device_report SET report_status=2 WHERE report_id={$reoprtid}";
					$this->db->query($updsql1);
					$updsql1 = "UPDATE t_device SET device_status=3 WHERE device_id={$list['device_id']}";
					$this->db->query($updsql1);
		       			exit(json_encode(array('code'=>0,'info'=>'维修任务下发成功')));
	       			}  
			}else{
				exit(json_encode(array('code'=>1,'info'=>'对不起,您无权限操作下发任务')));
			}
		}else{
			//撤销
			$sql = "select find_in_set({$id},has_role) as isexist from t_user WHERE user_id={$userid}";
			$role = $this->db->query($sql)->row_array();
			if(empty($role)){
				//不是指挥中心的人 推送到指挥中心，让指挥中心作出处理
				echo 1;
			}else{
				//指挥中心的人 把上报任务状态改为撤回 设备状态为正常
				$sql = "SELECT status FROM t_device_repairtask WHERE report_id={$reoprtid}";
				$status = $this->db->query($sql)->row_array();
				if($status['status']<>3){
					exit(json_encode(array('code'=>1,'info'=>'此任务不是超出范围的，不能撤回')));
				}
				$sql = "update t_device_report set is_show=0 WHERE report_id = {$reoprtid}";
				$res = $this->db->query($sql);
				$sql = "update t_device set device_status=1 WHERE device_id={$deviceid['device_id']}";
				$res1 = $this->db->query($sql);
				if($res && $res1){
					exit(json_encode(array('code'=>0,'info'=>'撤回成功')));
				}
			}
		}
	}
}